package com.dl.config.shiro;

import com.dl.config.jwt.JwtTokenManager;
import io.jsonwebtoken.Claims;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.apache.shiro.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * 自定义ShiroSession管理器
 * 1.解决单次请求需要多次访问redis
 * 2.集成jwt
 * @author DL
 * @create 2021-06-06 14:12
 */
public class ShiroSessionManager extends DefaultWebSessionManager {

    @Resource
    private JwtTokenManager jwtTokenManager;

    //从请求中获得sessionId的key
    private static final String AUTHORIZATION = "jwtToken";

    //自定义注入的资源类型名称
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    /**
     * 重写shiroSessionManager获得sessionId的方式
     * @param request
     * @param response
     * @return
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //1.判断request请求中是否包含jwtToken的key
        String jwtToken = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        //如果没有，走默认的cookie获得sessionId的处理方式
        if (jwtToken == null) {
            return super.getSessionId(request, response);
        }else {
            //如果有，走jwtToken获得sessionId的处理方式
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
            Claims claims = jwtTokenManager.deCodeToken(jwtToken);
            String id = (String) claims.get("jti");
            if (id != null) {
                request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
                //automatically mark it valid here.  If it is invalid, the
                //onUnknownSession method below will be invoked and we'll remove the attribute at that time.
                request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
                return id;
            }
            return super.getSessionId(request, response);
        }
    }

    /**
     * 解决shiro频繁更新session
     * @param key
     * @throws InvalidSessionException
     */
    @Override
    public void touch(SessionKey key) throws InvalidSessionException {
        Session session = doGetSession(key);
        if (session != null) {
            long oldTime = session.getLastAccessTime().getTime();
            session.touch(); // 更新访问时间
            long newTime = session.getLastAccessTime().getTime();
            if (newTime - oldTime > (1000 * 30)) { // 如果两次访问的时间间隔大于x分钟，主动持久化Session
                onChange(session);
            }
        }
    }

    /**
     * 解决shiro频繁读取session
     * @param sessionKey
     * @return
     * @throws UnknownSessionException
     */
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;
        if(sessionKey instanceof WebSessionKey) {
            request = ((WebSessionKey) sessionKey).getServletRequest();
        }
        if(request != null && sessionId != null) {
            Session session = (Session)request.getAttribute(sessionId.toString());
            if(session != null) {
                return session;
            }
        }
        Session session = super.retrieveSession(sessionKey);
        if(request != null && sessionId != null) {
            request.setAttribute(sessionId.toString(), session);
        }
        return session;
    }
}
